from twisted.protocols.basic import LineOnlyReceiver
import json
import commands

class CasterProtocol(LineOnlyReceiver):
    ''' Protocol to communicate with connected players '''

    def __init__(self):
        self.login = None
        self.creature_id = None
        self.committed = False
        self.loc_id = None
        
    @property
    def logged_in(self):
        if not self.login:
            self.send(commands.error("not logged in"))
            return False
        return True
    
    @property
    def joined(self):
        if not self.logged_in and not self.creature:
            self.send(commands.error("not joined"))
            return False
        return True
    
    @property
    def in_game(self):
        if not self.loc_id and not self.joined:
            self.send(commands.error("not in game"))
            return False
        return True

    def connectionMade (self):
        pass
        #self.sendLine('{"version":0.1}')
        
    def lineReceived (self, line):
        print "received:",line
        commands.do(self, line)
        
    def send(self, *args):
        self.sendLine(json.dumps(args))
            

    def connectionLost (self, reason):
        # TODO: Issue disappear request
        pl=self.factory.players
        if self.login in pl:
            del pl[self.login]
        self.disconnect()

    def disconnect(self, reason=None):
        if self.transport.connected:
            if reason:
                self.send({"what":"exit","msg":reason})
            self.transport.loseConnection()
        
    def __str__(self):
        try:
            ip = self.transport.getPeer()
        except:
            ip = "None"
        return 'Protocol<{0}:{1}>'.format(self.login, ip)
    
    def __repr__(self):
        return self.__str__()
